import React from 'react';
import FetchController from "fetch";
import {getQueryParams} from "auxiliaries/extends/format";
import {TokenAuthAction} from "auxiliaries/session/overload/token";
import {loaded, notify} from "components/state/toast";
import {REQUEST_STATE} from "fetchState";
import {observable} from "mobx";
import {PageStore} from 'auxiliaries/session/overload/storage';
import {WeChat} from "auxiliaries/extends/wechat";

class ComponentExtend extends React.Component {
    @observable User = {NonLogin: true};

    constructor(props, context) {
        super(props, context);

        this.queryString = {};

        this.queryString = getQueryParams();
        // let search = this.props.location.search;
        // if (search?.charAt(0) === '?') {
        //     search = search.substr(1, search.length + 1);
        //     search.split('&').forEach(x => {
        //         let params = x.split('=');
        //
        //         this.queryString[params[0]] = decodeURIComponent(params[1]);
        //     });
        // }
    }

    to(url) {
        let history = this.props.history;
        if (history.action === 'PUSH') {
            history.goBack();
        } else {
            history.replace(this.linkTo(url));
        }
    };

    go(url) {
        this.props.history.push(url);
    }

    // noinspection JSMethodCanBeStatic
    redirectLoginPage(){
        TokenAuthAction.RedirectLoginPage();
    }

    linkTo(link) {
        let keys = Object.keys(this.queryString);
        return this.props.history.createHref({
            pathname: link,
            search: `?` + keys.map(x => `${x}=${encodeURIComponent(this.queryString[x])}`).join('&')
        });
    }

    async setUserInfo(userOptions = {redirect: true, redirectBy401: true, showMessage: true}) {
        if (PageStore.get('UpdateUserInfo')) {
            //基于平台人才的资料更新，这里需要一波刷新用户资料
            PageStore.remove('UpdateUserInfo');
            await TokenAuthAction.RefreshUser();
        }
        this.User = await TokenAuthAction.GetUser(userOptions);
    }

    // noinspection JSMethodCanBeStatic
    SimplingRequest({DATA, STATUS, CODE, MESSAGE, DETAILS}, options = {}) {
        if (CODE === REQUEST_STATE.CANCEL) {
            return false;
        }

        if (STATUS === 0) {
            return {DATA, STATUS};
        } else {
            if (options?.all?.noNotify === true) {
                return {DATA, STATUS};
            }
            if (options?.[STATUS]?.['noNotify']) {
                return {DATA, STATUS};
            }
            options?.[STATUS]?.['action']?.(DATA);
            notify(DETAILS || MESSAGE);
            return {DATA, STATUS};
        }
    }

    // noinspection JSMethodCanBeStatic
    SimplingRequestBoolean({DATA, STATUS, CODE, MESSAGE, DETAILS}) {
        if (CODE === REQUEST_STATE.CANCEL) {
            return -1;
        }

        if (STATUS === 0) {
            return true;
        } else {
            notify(DETAILS || MESSAGE);
            return false;
        }
    }

    onPush(link, e) {
        e?.stopPropagation();
        e?.preventDefault();
        this.props.history.push(link);
    }

    onReplace(link, e) {
        e?.stopPropagation();
        e?.preventDefault();
        this.props.history.replace(link);
    }

    updateProperty(keys, value, ...rest) {
        let props = this;
        let split = keys.split('.');
        let arrayLength = split.length - 1;

        if (typeof value === 'function') {
            let temp = !!rest[0]?.currentTarget ? rest[0]?.currentTarget?.value : rest[0];
            value = value(temp, rest[0]);
        }

        split.forEach((key, index) => {
            if (index >= arrayLength) {
                if (!!value?.currentTarget) {
                    props[key] = value.currentTarget.value;
                } else {
                    props[key] = value;
                }
            } else {
                props = props[key] || {};
            }
        });
    }

    setState(...args) {
        if (this.updater.isMounted(this)) {
            return super.setState.apply(this, args);
        } else {
            console.info('不渲染')
        }
    };

    async componentDidMount() {
        await WeChat.Initialize();
    }

    componentWillMount() {

    }

    componentWillUnmount() {
        window.scrollTo(0, 0);
        FetchController.close();
        loaded();
    }
}

export default ComponentExtend;